package com.zd.hamster.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;

public class Hamster {

	private final static String PATH = "/f";

	private String host;

	private int port;

	private String url;
	
	private FileUploader uploader = new FileUploader();
	
	private FileDownloader downloader = new FileDownloader();
	
	private FileDeleter deleter = new FileDeleter();

	public Hamster(String host) {
		this(host, 81);
	}

	public Hamster(String host, int port) {
		this.host = host;
		this.port = port;
		this.url = String.format("http://%s:%d%s", host, port, PATH);
	}

	/**
	 * 上传文件
	 * 
	 * @param group    分组
	 * @param in       上传文件流
	 * @param filename 上传的文件名称
	 * @return Key
	 * @throws IOException
	 */
	public String up(InputStream in, String filename, String group) throws IOException {
		group = group == null ? "" : group;
		String result = uploader.up(url + "?group=" + group, in, filename);
		ObjectMapper mapper = new ObjectMapper();
		Map<?, ?> map = mapper.readValue(result, Map.class);
		return String.valueOf(map.get("data"));
	}
	
	/**
	 * 覆盖上传
	 * @param group
	 * @param in
	 * @param filename
	 * @return
	 * @throws IOException
	 */
	public String cover(InputStream in, String filename, String group, String key) throws IOException {
		group = group == null ? "" : group;
		return uploader.cover(String.format("%s?key=%s&group=%s", url, key, group), in, filename);
	}

	/**
	 * 下载
	 * 
	 * @param group
	 * @param key
	 * @param out
	 * @throws IOException
	 */
	public void down(OutputStream out, String group, String key) throws IOException {
		group = group == null ? "" : group;
		downloader.down(String.format("%s/%s?group=%s", url, key, group), out);
	}
	
	/**
	 * 下载
	 * @param out
	 * @param key
	 * @param group
	 * @param version
	 * @throws IOException
	 */
	public void downVersion(OutputStream out, String group, String key, int version) throws IOException {
		group = group == null ? "" : group;
		downloader.down(String.format("%s/%s?group=%s&version=%d", url, key, group, version), out);
	}


	/**
	 * 删除
	 * @param group
	 * @param key
	 * @throws IOException
	 */
	public void delete(String group, String key) throws IOException {
		group = group == null ? "" : group;
		deleter.del(String.format("%s?key=%s&group=%s", url, key, group));
	}

	public String getHost() {
		return host;
	}

	public int getPort() {
		return port;
	}
}
